<template>
	<div>
		<el-drawer v-model="deptDrawer" :direction="direction" :before-close="handleDeptDataClose">
			<template #header>
				<span>{{ state.title }}</span>
			</template>
			<div>
				<el-form ref="deptDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="90px">
					<el-row>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="部门名称" prop="deptName">
								<el-input v-model="state.ruleForm.deptName" placeholder="请输入部门名称" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="上级部门" prop="parentId">
								<el-cascader
									:options="state.deptData"
									:props="{ checkStrictly: true, value: 'id', label: 'deptName', emitPath: false }"
									placeholder="请选择父部门"
									clearable
									class="w100"
									v-model="state.ruleForm.parentId"
								>
									<template #default="{ node, data }">
										<span>{{ data.deptName }}</span>
										<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
									</template>
								</el-cascader>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="部门排序" prop="deptSort">
								<el-input v-model.number="state.ruleForm.deptSort" placeholder="请输入部门排序" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="部门描述" prop="description">
								<el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入部门描述" maxlength="150"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="handleDeptDataClose" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(deptDialogFormRef)" size="default">{{ state.submitTxt }}</el-button>
				</div>
			</template>
		</el-drawer>
	</div>
</template>

<script setup lang="ts" name="deptDialog">
import { reactive, ref, nextTick } from 'vue';
import { deptApi } from '/@/api/sys/dept/index';
import msg from '/@/utils/messageUtils';
import type { FormInstance, FormRules } from 'element-plus';
const deptDrawer = ref(false);
const direction = ref('rtl');
const deptDialogFormRef = ref();
const emit = defineEmits(['refreshDept']);
const state = reactive({
	title: '新增部门',
	submitTxt: '新增',
	ruleForm: {
		id: '',
		deptName: '',
		parentId: '',
		description: '',
		deptSort: 0,
	},
	deptData: [],
	type: 'add',
});

const rules = reactive<FormRules>({
	// id: [],
	deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
	parentId: [{ required: true, message: '父部门不能为空', trigger: 'blur' }],
	deptSort: [
		{ required: true, message: '部门排序不能为空', trigger: 'blur' },
		{ type: 'number', message: '排序字段必须数字' },
	],
});
const handleDeptDataClose = () => {
	deptDrawer.value = false;
};

const openDialog = (type: string, row: any) => {
	deptDrawer.value = true;
	state.type = type;
	if (type === 'edit') {
		state.title = '更新部门';
		state.submitTxt = '修改';
		state.ruleForm.id = row.id;

		viewDept(row.id);
		nextTick(() => {
			deptDialogFormRef.value.clearValidate();
		});
	} else {
		state.title = '新增部门';
		state.submitTxt = '新增';
		nextTick(() => {
			deptDialogFormRef.value.resetFields();
			deptDialogFormRef.value.clearValidate();
			state.ruleForm.parentId = row.id;
		});
	}
	getDeptData();
};

const viewDept = async (deptId: string) => {
	try {
		const { data } = await deptApi().viewDept(deptId);
		state.ruleForm.deptSort = data.deptSort;
		state.ruleForm.description = data.description;
		state.ruleForm.deptName = data.deptName;
		state.ruleForm.parentId = data.parentId;
	} catch (error) {
		msg().error('获取部门详细失败');
	}
};
const getDeptData = async () => {
	try {
		const { data } = await deptApi().tree();
		state.deptData = data;
	} catch (error) {
		msg().error('获取部门失败，请重试.');
	}
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			try {
				if (state.type === 'edit') {
					await deptApi().updateDept(state.ruleForm);
				} else {
					await deptApi().createDept(state.ruleForm);
				}
				msg().success('操作成功');
				handleDeptDataClose();
				emit('refreshDept');
			} catch (error) {
				msg().error('操作失败,请重试');
			}
		}
	});
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped>
.dialog-footer {
	margin: 15px;
}
</style>
